<template>
  <ContentWrap>
    <ElForm
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入菜单名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in common_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:menu:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" />
          展开/折叠
        </el-button>
        <el-button plain @click="refreshMenu">
          <Icon class="mr-5px" icon="ep:refresh" />
          刷新菜单缓存
        </el-button>
      </el-form-item>
    </ElForm>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap>
    <ElAutoResizer>
      <template #default="{ width }">
        <el-table-v2
          v-loading="listLoading"
          v-model:expanded-row-keys="expandedRowKeys"
          :columns="columns"
          :data="list"
          expand-column-key="name"
          :height="tableHeight"
          :width="width"
          fixed
          row-key="id"
        />
      </template>
    </ElAutoResizer>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MenuForm ref="editFormRef" @success="getList" />
</template>

<script setup lang="tsx">
import * as MenuApi from '@/api/system/menu'
import MenuForm from './MenuForm.vue'
import { handleTree } from '@/utils/tree'
import { EnableStatusEnum, SystemMenuTypeEnum } from '@/utils/constants'
import type { MenuVO } from '@/api/system/menu'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { AnyColumn } from 'element-plus/es/components/table-v2/src/common'
import { TableV2FixedDir, ElSwitch, ElButton } from 'element-plus'
import { Icon } from '@/components/Icon'
import { DictTag } from '@/components/DictTag'
import { hasAnyPermi } from '@/utils/perm'
import { useAppStore } from '@/stores/modules/app'

defineOptions({ name: 'SystemMenu' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { wsCache } = useCache()
const appStore = useAppStore()
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const columns = [
  {
    key: 'name',
    title: '菜单名称',
    dataKey: 'name',
    width: 250,
    fixed: TableV2FixedDir.LEFT
  },
  {
    key: 'id',
    title: '菜单编号',
    dataKey: 'id',
    width: 115
  },
  {
    key: 'icon',
    title: '图标',
    dataKey: 'icon',
    width: 65,
    cellRenderer: ({ cellData: icon }) => <Icon icon={icon} />
  },
  {
    key: 'sort',
    title: '排序',
    dataKey: 'sort',
    width: 80
  },
  {
    key: 'permission',
    title: '权限标识',
    dataKey: 'permission',
    width: 300
  },
  {
    key: 'componentName',
    title: '组件名称',
    dataKey: 'componentName',
    width: 280
  },
  {
    key: 'component',
    title: '组件路径',
    dataKey: 'component',
    width: 300
    // maxWidth: 500,
  },
  {
    key: 'path',
    title: '路由地址',
    dataKey: 'path',
    width: 300
    // maxWidth: 500,
  },
  {
    key: 'status',
    title: '状态',
    dataKey: 'status',
    width: 100,
    fixed: TableV2FixedDir.RIGHT,
    cellRenderer: ({ rowData }) => {
      // 检查权限
      if (!hasAnyPermi(['system:menu:update'])) {
        return <DictTag options={common_enable_status} value={rowData.status} />
      }

      // 如果有权限，渲染 ElSwitch
      return (
        <ElSwitch
          v-model={rowData.status}
          active-value={EnableStatusEnum.Enabled}
          inactive-value={EnableStatusEnum.Disabled}
          loading={menuStatusUpdating.value[rowData.id]}
          class="ml-4px"
          onChange={(val) => handleStatusChanged(rowData, val as number)}
        />
      )
    }
  },
  {
    key: 'operations',
    title: '操作',
    width: 160,
    fixed: TableV2FixedDir.RIGHT,
    cellRenderer: ({ rowData }) => {
      // 定义按钮列表
      const buttons: any[] = []

      // 检查权限并添加按钮
      if (hasAnyPermi(['system:menu:update'])) {
        buttons.push(
          <ElButton key="edit" link type="primary" onClick={() => openForm('update', rowData.id)}>
            编辑
          </ElButton>
        )
      }
      if (hasAnyPermi(['system:menu:create'])) {
        buttons.push(
          <ElButton
            key="create"
            link
            type="primary"
            onClick={() => openForm('create', undefined, rowData.id, rowData.type)}
          >
            新增
          </ElButton>
        )
      }
      if (hasAnyPermi(['system:menu:delete'])) {
        buttons.push(
          <ElButton key="delete" link type="danger" onClick={() => handleDelete(rowData.id)}>
            删除
          </ElButton>
        )
      }
      // 如果没有权限，返回 null
      if (buttons.length === 0) {
        return null
      }
      // 渲染按钮列表
      return <>{buttons}</>
    }
  }
] as AnyColumn[]

const queryParams = reactive({
  name: undefined,
  status: undefined
})
const queryFormRef = ref()

const listLoading = ref(false) // 列表加载状态
const list = ref<any[]>([]) // 列表数据
const isExpandAll = ref(false) // 是否展开
const expandedRowKeys = ref<number[]>([]) // 展开行控制
const tableHeight = ref()

const getList = async () => {
  listLoading.value = true
  try {
    const data = await MenuApi.getMenuList(queryParams)
    list.value = handleTree(data)
    console.log(list.value)
  } finally {
    listLoading.value = false
  }
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  if (!isExpandAll.value) {
    const getMenuDirIds = (nodes: any[]): number[] => {
      const dirIds: number[] = []
      nodes.forEach((node) => {
        if (node.type === SystemMenuTypeEnum.Dir) {
          dirIds.push(node.id!)
          if (node.children?.length) {
            dirIds.push(...getMenuDirIds(node.children))
          }
        }
      })
      return dirIds
    }
    expandedRowKeys.value = getMenuDirIds(list.value)
    // expandedRowKeys.value = list.value.map((item) => item.id)
  } else {
    expandedRowKeys.value = []
  }
  isExpandAll.value = !isExpandAll.value
}

const refreshMenu = async () => {
  try {
    await message.confirm('即将更新缓存刷新浏览器！')
    // 清空本地缓存，触发刷新从新获取
    wsCache.delete(CACHE_KEY.USER)
    wsCache.delete(CACHE_KEY.ROLE_ROUTES)
    location.reload()
  } catch {}
}

const editFormRef = ref<InstanceType<typeof MenuForm>>()
const openForm = (type: string, id?: number, parentId?: number, menuType?: string) => {
  let withMenuType: string | undefined = undefined
  if (menuType === SystemMenuTypeEnum.Dir) {
    withMenuType = SystemMenuTypeEnum.Menu
  } else if (menuType === SystemMenuTypeEnum.Menu) {
    withMenuType = SystemMenuTypeEnum.Button
  }
  editFormRef.value?.open(type, id, parentId, withMenuType)
}

const handleDelete = async (id: number) => {
  try {
    // 弹出确认框
    await message.delConfirm()
    // 发起删除请求
    await MenuApi.deleteMenu(id)
    // 成功提示
    message.success(t('common.delSuccess'))
    // 刷新列表(页码不变)
    await getList()
  } catch {}
}

/** 开启/关闭菜单的状态 */
const menuStatusUpdating = ref({}) // 菜单状态更新中的 menu 映射。key：菜单编号，value：是否更新中
const handleStatusChanged = async (menu: MenuVO, val: number) => {
  try {
    const text = menu.status === EnableStatusEnum.Enabled ? '启用' : '停用'
    await message.confirm(`确认要"${text}""${menu.name}"菜单吗?`)
    // 1. 标记 menu.id 更新中
    menuStatusUpdating.value[menu.id!] = true
    try {
      // 2. 发起更新状态
      await MenuApi.updateMenuStatus(menu.id!, val)
    } finally {
      // 3. 标记 menu.id 更新完成
      menuStatusUpdating.value[menu.id!] = false
    }
  } catch {
    menu.status =
      menu.status === EnableStatusEnum.Enabled
        ? EnableStatusEnum.Disabled
        : EnableStatusEnum.Enabled
  }
}

const updateTableHeight = () => {
  const hasFooter = appStore.getFooter
  tableHeight.value = document.documentElement.clientHeight - 90 - 90 - (hasFooter ? 50 : 0) - 30
}

watch(
  () => appStore.getFooter,
  () => {
    updateTableHeight()
  }
)

onMounted(() => {
  updateTableHeight()
  getList()
})
</script>

<style scoped lang="scss"></style>
